
<template>
    <el-badge
      :value="unreadcount"
      class="item"
      :max="99"
      :offset="[-2, 0]"
      :show-zero="false"
      style="margin-right: 24px"
    >
      <img
        src="@/assets/message/message.png"
        style="width: 24px; cursor: pointer; height: 24px"
        @click="goMessage()"
        alt=""
      />
    </el-badge>
  </template>
  
  <script setup>
  import { ElNotification } from 'element-plus'
  import { http } from '@/utils/http'
  import config from '@/config'
  import WS from '@/utils/ws.js'
  
  const router = useRouter()
  const unreadcount = ref(0)
  let uncountIntervalId
  const userStore = useUserStore()
  const audio = new Audio()
  const ws = new WS({
    url: `ws://${userStore.wsenv}/info/message/`,
    onMessage(data) {
      if (data.level != undefined) {
        if (data.level !== 4) {
          audio.src = 'http://tools.app.qubit-dance.com/sound/defeat.mp3'
          audio.play()
        } else {
          audio.src = 'http://tools.app.qubit-dance.com/sound/success.mp3'
          audio.play()
        }
        ElNotification({
          title: '消息通知',
          icon: '',
          customClass: 'message_class',
          dangerouslyUseHTMLString: true,
          message: data.message,
  
          //  <div>
          //   <span style="margin-right: 8px;width: 32px;padding: 0 4px;height: 16px;background: ${
          //     colors[data.level]
          //   };color: #fff">${levels[data.level]}</span><span>${data.message}
          //   </span>
          // </div>
          onClick() {
            goMessage()
          },
        })
      }
    },
  })
  
  const levels = { 1: '普通', 2: '重要', 3: '警告', 4: '成功' }
  const colors = { 1: '#3711d8;', 2: '#ff5f58', 3: '#feac2e', 4: '#1cc535' }
  
  const goMessage = () => {
    router.replace('message')
    // if (config.isWeb) {
    //   window.open(`/#/message`)
    // } else {
    //   let a = {
    //     value: 'message',
    //     label: '消息中心',
    //   }
    //   window.SDK.send('openWeb', a)
    // }
  }
  
  const getunreadcount = () => {
    clearInterval(uncountIntervalId)
    http.get('/message/unread_count').then(res => {
      unreadcount.value = res.data.unread_count
      uncountIntervalId = setInterval(() => {
        getunreadcount()
      }, 10000)
    })
  }
  
  onMounted(() => {
    getunreadcount()
  })
  onUnmounted(() => {
    clearInterval(uncountIntervalId)
    ws.close()
    
  })
  </script>
  
  <style lang="scss" scoped>
  </style>
  
  <style>
  .message_class {
    width: 384px;
    padding: 20px 24px;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.2);
    background-color: #fff;
    border-radius: 0;
  }
  .message_class .el-notification__icon {
    display: none;
  }
  .message_class .el-notification__group {
    margin: 0;
  }
  .message_class .el-notification__content {
    margin-top: 16px;
  }
  </style>